<div class="table-stacked mt-8" role="table" aria-labelledby="taxonomies-title">
  <table class="table-list">
    <thead>
    <tr role="row">
      <th scope="col" role="columnheader" class="w-12"><span class="sr-only">Move</span></th>
      <th scope="col" role="columnheader">
        <ul class="taxonomy">
          <li><%= t("decidim.admin.taxonomies.name") %></li>
          <% if taxonomy.blank? %>
            <li><%= t("decidim.admin.taxonomies.total_items") %></li>
            <li><%= t("decidim.admin.taxonomies.total_filters") %></li>
          <% else %>
            <li><%= t("decidim.admin.taxonomies.count") %></li>
          <% end %>
          <li><%= t("decidim.admin.taxonomies.actions.actions") %></li>
        </ul>
      </th>
    </tr>
    </thead>
    <%#
     If you ever reach this template as source of inspiration for a table row drag and drop functionality,
     please take in to account that this is intended to manage a complex case, as it has the capability of nesting elements (a draggable within a draggable) so that you can reorder parents and children.
     In Decidim there are two ways to implement a sortable (but both use the same library html5sortable.es).

     The simpler one is just to add the [data-draggable-table] attribute in the parent element, it requires to also add the [data-sort-url] attribute. This URL will be used to send a PUT request and ignore the result.
    This implementation is used for instance in the admin's components table.

     For cases when you need more control you can use the second implementation, which is the one used here.
     It uses the "js-sortable" class to initialize the element and allows you to use all the options documented in https://github.com/lukasoppermann/html5sortable as [data-sortable-OPTION] in the html.
     Take into account, that, if using the second option, you need to implement the "sortupdate" event by yourself (see this file for an example). This allows you to control the return of the request for instance.
    %>
    <tbody class="js-sortable js-draggable-root" data-draggable-handle=".js-drag-handle" data-draggable-accept-from=".js-draggable-root" data-sort-url="<%= reorder_taxonomies_path %>" role="rowgroup">
      <% if path = path_to_prev_page(collection) %>
        <tr class="draggable-taxonomy change-page" data-prev-page="<%= path %>" data-taxonomy-id="<%= collection.page(collection.prev_page).per(per_page).last&.id %>"><td colspan="2"><%= t(".to_prev_page") %></td></tr>
      <% end %>

      <% collection.each do |taxonomy| %>
        <%= render "row", taxonomy:, with_children: !taxonomy.root? %>
      <% end %>
      <% if path = path_to_next_page(collection) %>
        <tr class="draggable-taxonomy change-page" data-next-page="<%= path %>" data-taxonomy-id="<%= collection.page(collection.next_page).per(per_page).first&.id %>"><td colspan="2"><%= t(".to_next_page") %></td></tr>
      <% end %>
    </tbody>
  </table>
</div>

<%= decidim_paginate collection %>

<script>
  document.addEventListener("turbo:load", () => {
    const sortables = document.querySelectorAll(".js-sortable");
    const nextPage = document.querySelector("[data-next-page]");
    const prevPage = document.querySelector("[data-prev-page]");
    const token = document.querySelector('meta[name="csrf-token"]');

    sortables.forEach(function(sortable) {
      sortable.addEventListener("sortupdate", function (event) {
        sortable.classList.add("spinner-container");
        const itemsId = Array.from(event.target.children).map(item => item.dataset.taxonomyId);
        const parentId = event.target.dataset.parentId || event.target.closest('[data-taxonomy-id]')?.dataset.taxonomyId || null;

        fetch(sortable.dataset.sortUrl, {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
            "X-CSRF-Token": token && token.getAttribute("content")
          },
          body: JSON.stringify({page: <%= collection.current_page %>, per_page: <%= per_page %>, ids_order: itemsId, parent_id: parentId})
        }).then(function(response) {
          if(response.ok) {
            // If moved on top of the next page, lets go to the next page
            if(!document.querySelector(".draggable-taxonomy:last-child").hasAttribute("data-next-page") && nextPage) {
              location.href = nextPage.dataset.nextPage;
            }
            // If moved on top of the previous page, lets go to the previous page
            else if(!document.querySelector(".draggable-taxonomy:first-child").hasAttribute("data-prev-page") && prevPage) {
              location.href = prevPage.dataset.prevPage;
            } else {
              sortable.classList.remove("spinner-container");
            }
          }
        });
      });
    });
  });
</script>
